<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Traits\ModelTree;
use Encore\Admin\Traits\AdminBuilder;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class Business extends Model
{
    //
    use ModelTree, AdminBuilder;

    protected $table = 'businesses';

    protected $fillable = ['name','description','order', 'parent_id'];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setParentColumn('parent_id');
        $this->setOrderColumn('order');
        $this->setTitleColumn('name');
    }

    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id');
    }
    //
    public function category()
    {
        return $this->belongsTo(BusinessCategory::class, 'category_id');
    }

    public function tasks()
    {
        return $this->hasMany(Task::class, 'business_id');
    }

    public function standards()
    {
        return $this->hasMany(Standard::class, 'business_id');
    }

    public function records()
    {
        return $this->hasMany(Record::class, 'business_id');
    }

    public static function getBusinessIdByDataCycle($data_cycle)
    {
        switch ($data_cycle){
            case '月':
                if (Cache::get('month_business_ids')){
                    return Cache::get('month_business_ids');
                }else{
                    $ids = DB::table('businesses')->where('data_cycle', '=', $data_cycle)->pluck('id');
                    Cache::put('month_business_ids',$ids);
                    return $ids;
                }
                break;
            case '季度':
                if (Cache::get('quarter_business_ids')){
                    return Cache::get('quarter_business_ids');
                }else{
                    $ids = DB::table('businesses')->where('data_cycle', '=', $data_cycle)->pluck('id');
                    Cache::put('quarter_business_ids',$ids);
                    return $ids;
                }
                break;
            case '半年':
                if (Cache::get('half_year_business_ids')){
                    return Cache::get('half_year_business_ids');
                }else{
                    $ids = DB::table('businesses')->where('data_cycle', '=', $data_cycle)->pluck('id');
                    Cache::put('half_year_business_ids',$ids);
                    return $ids;
                }
                break;
            case '年':
                if (Cache::get('year_business_ids')){
                    return Cache::get('year_business_ids');
                }else{
                    $ids = DB::table('businesses')->where('data_cycle', '=', $data_cycle)->pluck('id');
                    Cache::put('year_business_ids',$ids);
                    return $ids;
                }
                break;
        }
    }
}
